using UnityEngine;
using System.Collections;

namespace RichLabelSpace
{
	public class RichLabelEvent  
	{
        private string m_event_id = "";
        private bool  m_can_click = false;
        private RichLabelComponent m_comp = null;

        public string Id { get { return this.m_event_id; } }
        public bool CanClick { get { return this.m_can_click; } }

        public void Init() 
        {
            if(m_comp.m_ui_widget != null)
            {
                var widget = m_comp.m_ui_widget;
                var box = widget.GetComponent<BoxCollider>();
                var listen = widget.GetComponent<UIEventListener>();

                if(m_can_click)
                {
                    if (box == null) box = widget.gameObject.AddComponent<BoxCollider>();
                    box.center = new Vector3(widget.width / 2, 0, 0);
                    box.size = widget.localSize;
                    box.enabled = true;

                    if (listen == null) listen = widget.gameObject.AddComponent<UIEventListener>();
                    listen.onClick =  OnClick;
                }
                else
                {
                    if (box != null) box.enabled = false;
                }
            }
        }

        public void OnClick(GameObject go)
        {
            this.m_comp.m_ctrl.OnClick(this.m_event_id);
        }

        internal void AnalyticEvent(string rich_txt, RichLabelComponent comp)
        {
            this.m_comp = comp;
            var id = AnalyticEvent(rich_txt);
            if (id != null)
            {
                m_event_id = id;
                m_can_click = true;
            }
            else
            {
                m_event_id = null;
                m_can_click = false;
            }
        }

        internal RichLabelEvent(RichLabelEvent rich_event, RichLabelComponent comp)
        {
            this.m_event_id = rich_event.Id;
            this.m_can_click = rich_event.CanClick;
            this.m_comp = comp;
        }
        internal RichLabelEvent()
        {

        }

        /// <summary>
        /// 解析富文本
        /// </summary>
        /// <param name="rich_txt"></param>
        /// <returns></returns>
        private static string AnalyticEvent(string rich_txt)
        {
            /* private const */string ID_SYMBOL = "id";
            string[] rich_txts = RichTxtTool.SlipeString(rich_txt);
            if (rich_txts.Length > 0)
            {
                foreach (var txt in rich_txts)
                {
                    var strs = RichLabelComponent.GetPropertyValue(txt);
                    if (strs != null && strs.Length == 2 && strs[0] == ID_SYMBOL)
                    {
                        return strs[1];
                    }

                }
            }
            return null;
        }
    }
}